package com.jxtc.enterprise.tenant.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jxtc.enterprise.common.entity.Store;
import com.jxtc.enterprise.common.entity.Tenant;
import com.jxtc.enterprise.common.mapper.StoreMapper;
import com.jxtc.enterprise.common.mapper.TenantMapper;
import com.jxtc.enterprise.common.utils.CurrencyUtil;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import com.jxtc.enterprise.tenant.service.ExternalCallService;
import com.jxtc.enterprise.tenant.vo.req.MerchantPasswordUpdateReqVo;
import com.jxtc.enterprise.tenant.vo.req.RiderUpdateReqVo;
import com.jxtc.enterprise.tenant.vo.resp.StoreInfoRespVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 供外部服务调用的接口
 */
@RestController
@RequestMapping("/jxtc/enterprise/tenant/externalCall")
@RequiredArgsConstructor
@Slf4j
public class ExternalCallController {

    private final ExternalCallService externalCallService;

    private final TenantMapper tenantMapper;
    private final StoreMapper storeMapper;

    /**
     * 认证服务调用该接口更新店主在团餐系统中店铺的密码（该密码仅作为在租户管理平台/店铺管理页面密码展示用）
     */
    @PostMapping("/editMerchantPassword")
    public Result<Void> editMerchantPassword(@Valid @RequestBody MerchantPasswordUpdateReqVo reqVo) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, tenant view, /editMerchantPassword, request body: {}", requestId, JSONObject.toJSONString(reqVo));
        externalCallService.editMerchantPassword(reqVo);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 认证服务调用该接口更新配送员在团餐系统中的密码或名称
     */
    @PostMapping("/editRider")
    public Result<Void> editRider(@Valid @RequestBody RiderUpdateReqVo reqVo) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, tenant view, /editRider, request body: {}", requestId, JSONObject.toJSONString(reqVo));
        externalCallService.editRider(reqVo);
        return ResultGenerator.genSuccessResult();
    }


    /**
     * 认证服务调用该接口通过租户 ID 获取租户手机号
     */
    @GetMapping("/queryTenantPhoneById")
    public Result<String> queryTenantPhoneById(@RequestParam("tenantId") String tenantId) {
        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<Tenant>()
                .eq(Tenant::getId, tenantId)
                .select(Tenant::getPhone);
        Tenant tenantEntity = tenantMapper.selectOne(queryWrapper);
        if (tenantEntity == null) {
            // 如果租户信息不存在，返回错误提示信息
            throw new IllegalArgumentException("ID 为" + tenantId + " 的租户不存在");
        }
        return ResultGenerator.genSuccessResult(tenantEntity.getPhone());
    }


    /**
     * 认证服务调用该接口通过商户手机号和租户手机号来获取店铺信息，租户手机号用于跨系统验证店铺是否属于该租户
     */
    @GetMapping("/queryStoreInfoByPhone")
    public Result<StoreInfoRespVo> queryStoreInfoByPhone(@RequestParam("merchantPhone") String merchantPhone, @RequestParam("tenantPhone") String tenantPhone) {
        LambdaQueryWrapper<Store> storeEntityQueryWrapper = new LambdaQueryWrapper<Store>()
                .eq(Store::getMerchantPhone, merchantPhone)
                .eq(Store::getDelFlag, false)
                // 根据店铺创建时间降序
                .orderByDesc(Store::getCreateTime);
        List<Store> storeEntityList = storeMapper.selectList(storeEntityQueryWrapper);
        if (storeEntityList.isEmpty()) {
            // 如果查询不到手机号关联的店铺记录，返回错误提示信息
            throw new IllegalArgumentException("该手机号未注册店铺");
        }

        // 根据店铺信息中的租户 ID 查询租户手机号列表
        List<String> tenantIdList = storeEntityList.stream()
                .map(Store::getTenantId)
                .collect(Collectors.toList());
        LambdaQueryWrapper<Tenant> tenantEntityQueryWrapper = new LambdaQueryWrapper<Tenant>()
                .in(Tenant::getId, tenantIdList)
                .select(Tenant::getId, Tenant::getPhone);
        List<Tenant> tenantEntityList = tenantMapper.selectList(tenantEntityQueryWrapper);
        // 判断当前要同步数据的租户，是否同步的是属于租户自己的店铺的数据
        Optional<Tenant> tenantOptional = tenantEntityList.stream()
                .filter(tenant -> tenant.getPhone().equals(tenantPhone))
                .findFirst();

        // 如果租户手机号列表中包含 tenantPhone
        // 说明租户需要同步的店铺信息属于租户自己，此时 "销售价", "合作价" 也同步
        boolean syncPrice = tenantOptional.isPresent();
        String tenantId = tenantOptional.map(Tenant::getId).orElse("");

        // 如果租户自己的店铺数据存在，则同步租户自己的店铺数据
        // 否则以最新的店铺信息为准
        // 即：优先自己的店铺数据，否则取最新店铺数据
        Store storeEntity = storeEntityList.stream()
                .filter(store -> store.getTenantId().equals(tenantId))
                .findFirst()
                .orElse(storeEntityList.get(0));
        List<String> foodTypeNameList = Collections.emptyList();
        if (StringUtils.hasText(storeEntity.getFoodTypes())) {
            foodTypeNameList = JSONArray.parseArray(storeEntity.getFoodTypes(), String.class);
        }

        StoreInfoRespVo respVo = new StoreInfoRespVo();
        respVo.setStoreName(storeEntity.getName());
        respVo.setStoreImage(storeEntity.getLogo());
        respVo.setStoreQualification(storeEntity.getQualifications());
        respVo.setFoodTypes(foodTypeNameList);
        respVo.setStoreDescription(storeEntity.getDescription());
        respVo.setStoreAddress(storeEntity.getAddress());
        respVo.setStoreLongitude(storeEntity.getLongitude().toString());
        respVo.setStoreLatitude(storeEntity.getLatitude().toString());
        respVo.setPrinterType(storeEntity.getPrintLabelType());
        respVo.setPrinterSn(storeEntity.getPrinterSn());
        respVo.setMergeFoodItem(storeEntity.getMergeFoodItems());
        respVo.setMerchantName(storeEntity.getMerchantName());
        respVo.setMerchantPhone(storeEntity.getMerchantPhone());
        respVo.setMerchantLoginPassword(storeEntity.getMerchantLoginPasswd());
        respVo.setMerchantIdNum(storeEntity.getMerchantIdNum());
        respVo.setMerchantWechatNum(storeEntity.getMerchantWechatNum());
        respVo.setCategoryId(storeEntity.getCategoryId());
        respVo.setCategoryName(storeEntity.getCategoryName());
        respVo.setBusinessStart(storeEntity.getBusinessStart());
        respVo.setBusinessEnd(storeEntity.getBusinessEnd());
        respVo.setLimitCount(storeEntity.getLimitCount());

        if (syncPrice) {
            // 如果租户手机号列表中包含 tenantPhone
            // 说明租户需要同步的店铺信息属于租户自己，此时 "合作价" 也同步
            respVo.setStorePrice(CurrencyUtil.fenToYuan(storeEntity.getStorePrice()));
        }

        return ResultGenerator.genSuccessResult(respVo);
    }
}
